/**
 * @file syscall.c
 * @author etcflywy@126.com
 * @brief 
 * @version 0.1
 * @date 2025-11-09
 * 
 * @copyright Copyright (c) 2025
 * 
 */
#include "syscall.h"


// 系统调用号定义
#define SYS_WRITE 4
#define SYS_EXIT  1
#define SYS_SLEEP 162

// 文件描述符
#define STDOUT 1



// 系统调用函数
static int syscall(int num, int arg1, int arg2, int arg3) 
{
    int ret;
    asm volatile (
        "int $0x80"
        : "=a" (ret)
        : "a" (num), "b" (arg1), "c" (arg2), "d" (arg3)
        : "memory"
    );
    return ret;
}

// 计算字符串长度
static int strlen(const char *str) 
{
    int len = 0;
    while (str[len] != '\0') {
        len++;
    }
    return len;
}

// 打印函数
void kputs(const char *str) 
{
    int len = strlen(str);
    syscall(SYS_WRITE, STDOUT, (int)str, len);
}

void kputchar(int ch) 
{
    syscall(SYS_WRITE, STDOUT, (int)&ch, 1);
}

// 退出函数
void exit(int status) 
{
    syscall(SYS_EXIT, status, 0, 0);
    while(1) {}
}

// sleep 函数 - 休眠指定秒数
void sleep(unsigned int seconds) 
{
    struct timespec req, rem;
    
    req.tv_sec = seconds;
    req.tv_nsec = 0;
    
    // nanosleep 系统调用
    syscall(SYS_SLEEP, (int)&req, (int)&rem, 0);
}

// 毫秒级休眠
void msleep(unsigned int milliseconds) 
{
    struct timespec req, rem;
    
    req.tv_sec = milliseconds / 1000;
    req.tv_nsec = (milliseconds % 1000) * 1000000L;
    
    syscall(SYS_SLEEP, (int)&req, (int)&rem, 0);
}
